<?php

namespace App\Models\Order;

use App\Models\Setting;
use App\Models\Store;
use Carbon\Carbon;
use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

/**
 * 订单自动签收记录表
 *
 * @property int customer_id
 * @property int $order_id
 * @property bool signed
 * @property-read Order order
 * @property Carbon should_sign_at
 * @property Carbon created_at
 *
 * @mixin Builder
 */
class OrderAutoSign extends Model
{
    const AUTO_SIGN_DELAY_MINUTE_DEFAULT = 10080; // 60min * 24h * 7d

    protected $table = 'order_auto_sign';
    protected $guarded = [];
    protected $primaryKey = 'order_auto_sign_id';

    protected $casts = [
        'order_id'       => 'int',
        'signed'         => 'boolean',
        'should_sign_at' => 'datetime',
    ];

    /**
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function order()
    {
        return $this->belongsTo(Order::class, 'order_id', 'order_id');
    }

    /**
     * @param int $store_id
     *
     * @return int
     */
    static public function getDelayMinute(int $store_id = Store::STORE_ID_DEFAULT): int
    {
        return Setting::findConfigByKey(Setting::KEY_CONFIG_AUTO_SIGN_DELAY, $store_id)->value
            ??  OrderAutoSign::AUTO_SIGN_DELAY_MINUTE_DEFAULT;
    }

    /**
     * @param bool $signed
     *
     * @return int
     */
    public function updateSign(bool $signed)
    {
        return $this->update([
            'signed' => $signed
        ]);
    }
}
